package cn.wzx.service;

import cn.wzx.entity.MyUser;
import cn.wzx.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    UserMapper userMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    // 添加用户
    @Override
    public void addUser(MyUser user) {
        String password = user.getPassword();
        if (password != null || password.length() > 0) // 如果有密码传入
            user.setPassword(passwordEncoder.encode(password)); // 密码加密
            userMapper.addUser(user);
    }

    //用户全查询及分页
    @Override
    public List<Map<String, Object>> findAll(Integer start, Integer num) {
        Map<String, Object> map = new HashMap<>();
        map.put("start", start*num);
        map.put("num", num);
        return userMapper.findAll(map);
    }

    //查询总行数
    @Override
    public int count() {
        return userMapper.count();
    }

    //根据用户ID修改信息，如果修改了密码密码要加密处理
    @Override
    public void update(Map map) {
        String password = (String)map.get("password");
        if (password != null && password.length() > 0) {
            password = passwordEncoder.encode(password);
            map.put("password", password);
        }
        userMapper.update(map);
    }

    // 根据ID查询
    @Override
    public MyUser findById(Integer id) {
        return userMapper.findById(id);
    }
}
